# -*- coding: utf-8 -*-
# @Author : HaleShi
# @Time : 2023-05-31
# @File : 11_payout_cart.py

import time
import uuid
import ctypes
import json
import base64
import random
import requests
from urllib.parse import unquote_plus, quote_plus


def r(data_string):
    def int_overflow(val):
        maxint = 2147483647
        if not -maxint - 1 <= val <= maxint:
            val = (val + (maxint + 1)) % (2 * (maxint + 1)) - maxint - 1
        return val

    def unsigned_right_shitf(n, i):
        # 数字小于0，则转为32位无符号uint
        if n < 0:
            n = ctypes.c_uint32(n).value
        # 正常位移位数是为正数，但是为了兼容js之类的，负数就右移变成左移好了
        if i < 0:
            return -int_overflow(n << abs(i))
        # print(n)
        return int_overflow(n >> i)

    char_list = []
    aae = ['K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'U', 'V',
           'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'e', 'f', 'g', 'h',
           'i', 'j', 'k', 'l', 'm', 'n', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/']
    bArr = data_string.encode('utf-8')
    for i in range(0, len(bArr), 3):
        bArr2 = [None for i in range(4)]
        b2 = 0
        for i2 in range(0, 3):
            i3 = i + i2
            if i3 <= len(bArr) - 1:
                bArr2[i2] = b2 | unsigned_right_shitf((bArr[i3] & 255), ((i2 * 2) + 2))
                b2 = unsigned_right_shitf(((bArr[i3] & 255) << (((2 - i2) * 2) + 2)) & 255, 2)
            else:
                bArr2[i2] = b2
                b2 = 64
        bArr2[3] = b2
        for i4 in range(4):
            if bArr2[i4] <= 63:
                char_list.append(aae[bArr2[i4]])
            else:
                char_list.append("=")

    return "".join(char_list)


def encode_cipher(cipher_dict):
    for k, v in cipher_dict.items():
        cipher_dict[k] = r(v)


def gen_cipher_ep(uid, aid, open_udid, ts):
    cipher_dict = {
        "area": "20_1726_1734_23005",
        "d_model": "Pixel2XL",
        "wifiBssid": "unknown",
        "osVersion": "10",
        "d_brand": "Google",
        "screen": "2712*1440",
        "uuid": uid,
        "aid": aid,
        "openudid": open_udid,
    }
    encode_cipher(cipher_dict)
    data_dict = {
        "hdid": "JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=",
        "ts": ts,
        'ridx': -1,
        'cipher': cipher_dict,
        'ciphertype': 5,
        "version": "1.2.0",
        'appname': "com.jingdong.app.mall"
    }
    ep = json.dumps(data_dict, separators=(',', ':'))

    return ep


def gen_sign(function_id, body, uid):
    import subprocess
    cmd = f"java -jar  unidbg-0.9.7.jar {function_id} '{body}' {uid}"
    signature = subprocess.check_output(cmd, shell=True, cwd="unidbg_parent_jar")
    data_string = signature.strip().decode('utf-8').split("\n")[-1]
    return {item.split("=")[0]: item.split("=")[1] for item in data_string.split("&")}


def write_file_data(data_dict):
    times = time.strftime("%Y%m%d-%H-%M-%S")
    content_path_name = "./logs/wareBusiness/{}_content.json".format(times)
    print("————————————数据获取中，请稍等————————————")
    with open(content_path_name, 'w') as f:
        f.write(json.dumps(data_dict.text))



def run():
    aid = str(uuid.uuid4()).replace("-", "")
    uid = aid
    open_udid = aid
    ts = int(time.time() * 1000)
    ep = gen_cipher_ep(aid, uid, open_udid, ts)

    function_id = "cartCheckAll"

    cart_uuid = str(uuid.uuid4())
    body = '{"addressId":"119752937","appleCare":0,"businessId":"","cartBundleVersion":"10440","cartuuid":"%s","coord_type":"","cvhv":"213733304749710","hitNewUIStatus":1,"homeWishListUserFlag":"3","latitude":"24.492722","longitude":"110.398818","mqTriggerStatus":"0","operations":[{"carttype":"7"}],"syntype":"1","updateTag":false,"userType":"2"}'%(cart_uuid,)
    r_body = r(body)

    body_template_dict = {
        "hdid": "JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=",
        "ts": int(time.time() * 1000),
        'ridx': -1,
        'cipher': {"body": r_body},
        'ciphertype': 5,
        "version": "1.2.0",
        'appname': "com.jingdong.app.mall"
    }
    body_string = json.dumps(body_template_dict, separators=(',', ':'))

    sign_dict = gen_sign(function_id, body, uid)

    res = requests.post(
        url="https://api.m.jd.com/client.action",
        params={
            "functionId": function_id,
            "clientVersion": "10.4.4",
            "build": "93860",
            "client": "android",
            "partner": "tencent",
            "sdkVersion": "29",
            "lang": "en_US",
            "harmonyOs": "0",
            "networkType": "wifi",
            "uemps": "0-0",
            "ext": '{"prstate":"0","pvcStu":"1"}',
            "ef": "1",
            "ep": ep,
            'bef': "1",  # 注意事项
            "st": sign_dict['st'],
            "sign": sign_dict['sign'],
            "sv": sign_dict['sv'],
        },
        data='body={}&'.format(quote_plus(body_string)),
        headers={
            "user-agent": "okhttp/3.12.1;jdmall;android;version/10.4.4;build/93860;",
            'content-type': "application/x-www-form-urlencoded; charset=UTF-8",
            'cookie': 'wskey=AAJkdaV5AEAkARvazRqMu8zrfg6LRfCh9oEfway0wsremcm7TwR6H_S8y4jMBGQTlpVe0M3fWlrDKj3x3hoKRPegoe3Imlee;whwswswws=JD012145b9aDJ92fWGeY168543152439306HnJ2B8dN-Qo-KV_07mnfF4zGoa1oPQktGsCKOWqbRfL_oO6SPAXuoNpEKTyLZxYjFvZQCIIr7i9kantX40V8xgK3JjpPoMuQA3x9Hfzylog0t0tbxm~hbUWvISpmE2AudPAoLyMnJO6ocgLC-PRkgWqODALnQSjSNkQR271XQ-j_1bpHMxYlDjCXBmL3MfLkVGZPPx8Hm6csIWT0LiGRldBASmIZY6OnouHocQNxZZovHTL66FZ0jQRJuCLEDVwnRdvsi1UtV9Gg7QE_qdNRef9fK9FADsg;unionwsws={"devicefinger":"eidAd2ea812264sa21\/WfL3CSyqQLLXeriS9w9tf2AUpOnFjc4ZsEjP6rG+GdUcT1RsHBmQxrT2kWgRJGG7zGWGi9NKUcgvn7kaiPne8Hc9ucVJVhSxP","jmafinger":"JD012145b9aDJ92fWGeY168543152439306HnJ2B8dN-Qo-KV_07mnfF4zGoa1oPQktGsCKOWqbRfL_oO6SPAXuoNpEKTyLZxYjFvZQCIIr7i9kantX40V8xgK3JjpPoMuQA3x9Hfzylog0t0tbxm~hbUWvISpmE2AudPAoLyMnJO6ocgLC-PRkgWqODALnQSjSNkQR271XQ-j_1bpHMxYlDjCXBmL3MfLkVGZPPx8Hm6csIWT0LiGRldBASmIZY6OnouHocQNxZZovHTL66FZ0jQRJuCLEDVwnRdvsi1UtV9Gg7QE_qdNRef9fK9FADsg"};pin_hash=-1052766315;',
            'j-e-c': "%7B%22hdid%22%3A%22JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw%3D%22%2C%22ts%22%3A1685431672824%2C%22ridx%22%3A-1%2C%22cipher%22%3A%7B%22pin%22%3A%22c2VraQPfEJO5DG%3D%3D%22%7D%2C%22ciphertype%22%3A5%2C%22version%22%3A%221.2.0%22%2C%22appname%22%3A%22com.jingdong.app.mall%22%7D"
        },
    )

    write_file_data(res)

    data_dict = res.json()
    print(data_dict)
    print("选择购物车全部商品已经成功")
    exit()

if __name__ == '__main__':
    run()
